/*
 * Copyright 2010-2012 Susanta Tewari. <freecode4susant@users.sourceforge.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package barratt.cef.command;

import barratt.BarrattInterferenceModel;
import barratt.BarrattModelEstimator;
import barratt.cef.event.FitBarrattModelEvent;
import cef.command.Command;
import cef.command.CommandException;
import org.stat.model.data.Record;

import java.util.SortedMap;
import java.util.TreeMap;

/**
 *
 *
 * @version 1.3.0
 * @author Susanta Tewari
 * @history Created on 12/20/12
 * @since 1.3.0
 */
public class FitBarrattModelCommand extends Command<FitBarrattModelEvent> {

    /** Field description */
    private double k;

    /** Field description */
    private Record[] records;

    /** key: MSE; value: K */
    private SortedMap<Double, Double> mseMap;

    public FitBarrattModelCommand(final FitBarrattModelEvent event) {
        super(event);
    }

    @Override
    protected void executeImpl() throws CommandException, InterruptedException {

        final BarrattInterferenceModel barrattModel =
            new BarrattInterferenceModel(getEvent().getData());


        // search for best k
        mseMap = new TreeMap<>();

        BarrattModelEstimator barrattModelEstimator;

        for (int i = 0; i < 11; i++) {

            final double k = 0.1 * (i);

            barrattModelEstimator = new BarrattModelEstimator(k);

            barrattModel.setModelEstimator(barrattModelEstimator);

            final double mse = barrattModel.getMSE();

            mseMap.put(mse, k);
        }

        k                     = mseMap.get(mseMap.firstKey());
        barrattModelEstimator = new BarrattModelEstimator(k);

        barrattModel.setModelEstimator(barrattModelEstimator);
        barrattModel.runModel();

        records = barrattModel.getModelData().getRecords();
    }

    public double getK() {

        checkCmdFinished();

        return k;
    }

    /**
     * @return map with key: MSE; value: K
     */
    public SortedMap<Double, Double> getMseMap() {

        checkCmdFinished();

        return mseMap;
    }

    public Record[] getRecords() {

        checkCmdFinished();

        return records;
    }
}
